package com.wteam.config.JWT;

import com.alibaba.fastjson.JSONObject;
import com.wteam.untils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class Check implements HandlerInterceptor {
    @Override//目标方法执行前，返回Boolean
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {

        System.out.println("preHandle执行了");


        //1.获取请求url
        String url = req.getRequestURI().toString();
        log.info("请求url:{}",url);
        //2判断请求url是否包含login，如果包含放行
        if (url.contains("login")||url.contains("/regist")){
            log.info("登录放行：{}");
            return true;
        }

        //3看请求头令牌是否存在
        String jwt1 = req.getHeader("token");
        if (!StringUtils.hasLength(jwt1)){
            log.info("请求头为空");
            Result error = Result.token("Token_is_null");
            //手懂转换jasn格式
            String s = JSONObject.toJSONString(error);
            resp.getWriter().write(s);
            return false;
        }
//4看令牌是否出错
        try {
            jwt.parseJWT(jwt1);
        } catch (Exception e) {
            log.info("假的令牌");
            Result error = Result.token("your_token_is_false");
            //手懂转换jasn格式
            String s = JSONObject.toJSONString(error);
            resp.getWriter().write(s);
            return false;
        }

        log.info("令牌合法");
        return true;
    }

    @Override//目标方法执行后
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle");

    }

    @Override//视图渲染后，最后执行
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCOmpletion");

    }
}
